import axios from '@ohos/axios';
import protobuf from '@ohos/protobufjs';
import grpcResult from './model/grpcResult';
import { API_USER_AGENT, HOST } from '../core/dict';
import { danmakuSource } from '../danmaku/danmakuSource';

class request {
  async requestDmList(cid: number, type: number, index: number): Promise<grpcResult> {
    try {
      let res = await axios({
        method: "get",
        url: 'https://api.bilibili.com/x/v2/dm/list/seg.so',
        headers: {
          "referer": HOST,
          "app-key": "android64",
          "user-agent": API_USER_AGENT,
          "x-bili-aurora-zone": "sh001",
          "x-bili-aurora-eid": "UlMFQVcABlAH",
          "content-type": 'application/octet-stream'
        },
        params: {
          oid: cid,
          type: type,
          segment_index: index
        }
      });
      var result = new Uint8Array(res.data);
      if (result.byteLength > 0) {
        var builder = await protobuf.loadProtoFile('danmaku.proto', null, null, globalThis.resourceMana);
        // @ts-ignore
        var DmSegMobileReply = builder.build("bilibili.community.service.dm.v1.DmSegMobileReply");
        var reply = DmSegMobileReply.decode(result);
        let source = new danmakuSource(reply);
        return new grpcResult(0, '', source);
      } else
        return new grpcResult(-1, res.statusText);
    } catch (err) {
      return new grpcResult(-1, err.toString());
    }
  }
}
export default new request();